<script lang="ts">
export default {
  name: "DeviceEditDialog"
}
</script>

<!--
 * @Description: 设备编辑对话框
 * @version:
 * @Author:
 * @Date: 2022-10-24 09:10:28
 * @LastEditors:
 * @LastEditTime: 2022-10-24 09:10:28
-->
<template>
  <!-- 对话框 -->
  <el-dialog :close-on-click-modal="false" :model-value="visible" :title="dataState.title" min-width="200px"
             @close="handleCancel">

    <!-- 数据表单 -->
    <el-form ref="dataFormRef" :model="dataState.formData" :rules="dataState.rules" label-width="80px">

      <!-- 编辑框：设备名称 -->
      <el-form-item label="短名称" prop="shortName">
        <el-input v-model="dataState.formData.shortName" @input="handleInput" :disabled="dataState.type==='update'"/>
      </el-form-item>

      <el-form-item label="长名称" prop="modelName">
        <el-input v-model="dataState.formData.modelName" :disabled="true"/>
      </el-form-item>

      <!-- 下拉框：设备类型 -->
      <el-form-item label="引擎厂商" prop="engine.manufacturer">
        <el-select v-model="dataState.formData.modelParam.engine.manufacturer" placeholder="请选择"
                   @change="handleSelectManufacturer">
          <el-option
            v-for="item in dataState.manufacturerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>

        <!-- 下拉框：设备类型 -->
        <el-form-item label="引擎类型" prop="engine.deviceType">
          <el-select v-model="dataState.formData.modelParam.engine.deviceType" placeholder="请选择">
            <el-option
              v-for="item in dataState.deviceTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form-item>

      <!-- 下拉框：配置参数 -->
      <el-form-item label="配置参数" prop="modelParamJson">
        <el-input v-model="dataState.formData.modelParam.listJson" :autosize="{ minRows: 1, maxRows: 15 }" type="textarea"/>
      </el-form-item>

      <!-- 下拉框：配置参数 -->
      <el-form-item label="扩展参数" prop="extendParamJson">
        <el-input v-model="dataState.formData.extendParamJson" :autosize="{ minRows: 1, maxRows: 100 }" type="textarea"/>
      </el-form-item>

    </el-form>

    <!-- 脚部：确认/取消按钮-->
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCancel">取 消</el-button>
      </div>
    </template>

  </el-dialog>
</template>

<script lang="ts" setup>
import {nextTick, onMounted, reactive, ref} from "vue";

import {ElForm, ElMessage} from "element-plus";
import {DeviceModelItem, CreateDeviceModelRequestVO, DeviceModelParam} from "@/api/repo/comp/local/types";
import {listOption2List, listOptionList} from "@/api/option";
import {isEmpty, isNull} from "@/utils/fieldutil";

const props = defineProps(['visible']);
const emit = defineEmits(['create', 'update', 'cancel']); //注意：这个是父组件<dict-type-edit>标签上的@close
const dataFormRef = ref(ElForm); // 属性名必须和元素的ref属性值一致

/**
 * 对外声明接口：父页面可以调用它
 */
defineExpose({initEditData});

// 数据状态：定义
let dataState = reactive({
  // 类型：create/update
  type: 'create',
  // 标题
  title: '添加设备',

  fullNameStartTag: '',

  formData: {
    id: undefined,
    compId: 0,
    shortName:  '',
    modelName:  '',
    manufacturer:  '',
    deviceType:  '',
    modelParam: {},
    modelParamJson: '{}',
    extendParam: {},
    extendParamJson: '{}',
  } as CreateDeviceModelRequestVO,

  // 厂商类型选项
  manufacturerOptions: [] as OptionType[],
  // 设备类型选项
  deviceTypeOptions: [] as OptionType[],

  // 对话框的各控件输入规则
  rules: {
    shortName: [{required: true, message: '参数不能为空', trigger: 'blur'}],
    modelName: [{required: true, message: '参数不能为空', trigger: 'blur'}],
    modelParamJson: [{required: true, message: '参数不能为空', trigger: 'blur'}],
    extendParamJson: [{required: true, message: '参数不能为空', trigger: 'blur'}],
  },
});

/**
 * 设备类型下拉框
 * @taskParam value
 */
async function handleSelectManufacturer(value: any) {
  await listOption2List("OperateEntity", "manufacturer", value, 'deviceType').then(({data}) => {
    dataState.deviceTypeOptions = data;
    if (dataState.deviceTypeOptions.length > 0){
      dataState.formData.modelParam.engine.deviceType = dataState.deviceTypeOptions[0].value;
    }
  });
}


function handleInput(data: any) {
  if (dataState.formData.modelName.startsWith(dataState.fullNameStartTag) || dataState.formData.modelName === ''){
    dataState.formData.modelName = dataState.fullNameStartTag + data;
  }
}

function handleCancel() {
  //执行调用<device-edit-dialog @cancel="cancelEdit">
  emit('cancel', "子组件传给父组件的值");
}

/**
 * 确认：新增/修改实体
 */
function handleSubmit() {
  if (isEmpty(dataState.formData.shortName)) {
    return;
  }
  if (isEmpty(dataState.formData.modelParam.engine)) {
    return;
  }
  if (isEmpty(dataState.formData.modelParam.engine.manufacturer)) {
    return;
  }
  if (isEmpty(dataState.formData.modelParam.engine.deviceType)) {
    return;
  }

  // 调整为长名称
  if (dataState.formData.modelName.startsWith(dataState.fullNameStartTag)){
    dataState.formData.modelName = dataState.fullNameStartTag + dataState.formData.shortName;
  }
  if (dataState.formData.modelName === ''){
    dataState.formData.modelName = dataState.fullNameStartTag + dataState.formData.shortName;
  }

  try {
    if (dataState.formData.modelParam.listJson === undefined ||
      !dataState.formData.modelParam.listJson.startsWith('[') ||
      !dataState.formData.modelParam.listJson.endsWith(']')
    ) {
      ElMessage.info('配置参数的格式，不是合法的JSON格式!');
      return;
    }

    dataState.formData.modelParam.list = JSON.parse(dataState.formData.modelParam.listJson);
    dataState.formData.modelParam.listJson = undefined;
  } catch (e) {
    ElMessage.info('配置参数的格式，不是合法的JSON格式!');
    return;
  }

  try {
    if (dataState.formData.extendParamJson === undefined) {
      ElMessage.info('扩展参数的格式，不是合法的JSON格式!');
      return;
    }

    dataState.formData.extendParam = JSON.parse(dataState.formData.extendParamJson);
  } catch (e) {
    ElMessage.info('扩展参数的格式，不是合法的JSON格式!');
    return;
  }

  if (dataState.type === 'create') {
    // 执行调用<device-edit-dialog @create="createEdit">的create
    emit('create', dataState.formData);
  }
  if (dataState.type === 'update') {
    //执行调用<device-edit-dialog @update="updateEdit">
    emit('update', dataState.formData);
  }
}

/**
 * 初始化对话框
 * @taskParam type 对话框类型
 * @taskParam entity 实体
 */
function initEditData(type: string, compParam: any, entity: DeviceModelItem) {
  dataState.fullNameStartTag = compParam.manufacturer + '|' + compParam.deviceType + '|';

  if (type === 'create') {
    dataState.type = type;
    dataState.title = '新增设备';

    dataState.formData.id = undefined;
    dataState.formData.shortName = '';
    dataState.formData.modelName = '';
    dataState.formData.manufacturer = '';
    dataState.formData.deviceType = '';
    dataState.formData.modelParam = {
      engine : {
        manufacturer: '',
        deviceType: ''
      },
      list: [],
      listJson: '[]'
    } as DeviceModelParam;
    dataState.formData.extendParam = {};
    dataState.formData.extendParamJson = '{}';

    nextTick(() => {
      dataFormRef.value.resetFields();
    })
    return;
  }


  if (type === 'update') {
    dataState.type = type;
    dataState.title = '修改设备';


    dataState.formData.id = entity.id;
    dataState.formData.shortName = entity.modelName;
    dataState.formData.modelName = entity.modelName;
    dataState.formData.deviceType = entity.deviceType;
    dataState.formData.manufacturer = entity.manufacturer;
    dataState.formData.modelParam = {
      engine : entity.modelParam.engine,
      list: entity.modelParam.list,
      listJson: JSON.stringify(entity.modelParam.list, null, 5),
    } as DeviceModelParam;
    dataState.formData.extendParam = entity.extendParam;
    dataState.formData.extendParamJson = entity.extendParamJson;

    // 截断为短名称
    if (dataState.formData.modelName.startsWith(dataState.fullNameStartTag)){
      dataState.formData.shortName = dataState.formData.modelName.substring(dataState.fullNameStartTag.length,dataState.formData.modelName.length);
    }

    return;
  }
}

/**
 * 响应页面安装：页面的初始化工作
 */
onMounted(() => {
  // 查询厂商选项，并保存在存量区
  listOptionList("OperateEntity", "manufacturer").then(({data}) => {
    dataState.manufacturerOptions = data;
  });
  // 查询设备类型选项，并保存在存量区
  listOptionList("OperateEntity", "deviceType").then(({data}) => {
    dataState.deviceTypeOptions = data;
  });
});

</script>
